import { request } from '../request.js';

// https://cloud.baidu.com/doc/BODY/s/Fk3cpyxua
function getToken(params) {
  return new Promise((res) => {
    request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={请在文档中查找并修改}&client_secret={请在文档的帮助下修改}',
      method: 'post',
      params,
    }).then((result) => {
      res(result.access_token);
    });
  });
}

export async function parsePhoto(base64) {
  var token = await getToken();
  console.log('token', token);
  var url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=' + token;
  return request({
    url: url,
    method: 'post',
    params: {
      image: encodeURI(base64.replace(/^data:image\/\w+;base64,/, '')),
      type: 'foreground',
    },
    header: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
}

export function base64tofile(base64Str) {
  return new Promise((resolve, reject) => {
    // 后台返回的base64格式数据的回车换行换为空字符''
    let base64Image = base64Str.split(',')[1].replace(/[\r\n]/g, '');
    // 文件管理器
    const fsm = wx.getFileSystemManager();
    // 文件名
    const FILE_BASE_NAME = 'tmp_base64src';
    // 文件后缀
    const format = 'png';
    // 获取当前时间戳用于区分小程序码，防止多次写进的小程序码图片都一样，建议通过不同的列表ID来区分不同的小程序码
    const timestamp = new Date().getTime();
    // base转二进制
    const buffer = wx.base64ToArrayBuffer(base64Image),
      // 文件名
      filePath = `${wx.env.USER_DATA_PATH}/${timestamp}share.${format}`;
    // 写文件
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success(res) {
        // 读取图片
        wx.getImageInfo({
          src: filePath,
          success: function (res) {
            let img = res.path;
            // 把需要画出来的图片的临时url暴露出去
            resolve(img);
            reject();
          },
          fail(e) {
            console.log('读取图片报错');
            console.log(e);
          },
          error(res) {
            console.log(res);
          },
        });
      },
      fail(e) {
        console.log(e);
      },
    });
  }).catch((e) => {
    console.log(e);
  });
}
